package com.barney.support.web.test;

import java.io.File;
import java.util.List;

import org.mortbay.jetty.webapp.WebAppClassLoader;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Jetty 웹 서버 리스너
 */
public class JettyWebServerListener implements Scanner.BulkListener {

	private final Logger logger = LoggerFactory.getLogger(JettyWebServerListener.class);

	private final WebAppContext webAppContext;
	private final List<File> classpaths;

	/**
	 * 웹 서버 리스너
	 * @param webAppContext 웹 어플리케이션 컨텍스트
	 * @param classpaths 클래스 패스
	 */
	public JettyWebServerListener(WebAppContext webAppContext, List<File> classpaths) {
		super();
		this.webAppContext = webAppContext;
		this.classpaths = classpaths;
	}

	@Override
	public void filesChanged(@SuppressWarnings("rawtypes") List changes) throws Exception {
		try {
			webAppContext.stop();
			webAppContext.setClassLoader(null);
			webAppContext.setServerClasses(new String[] { "org.mortbay.jetty.plus.jaas.",
					"org.mortbay.jetty." });
			WebAppClassLoader loader = new WebAppClassLoader(webAppContext);
			for (File each : classpaths) {
				loader.addClassPath(each.getCanonicalPath());
			}

			webAppContext.setClassLoader(loader);

			webAppContext.start();
		} catch (Exception e) {
			logger.error("Error reconfiguring/restarting webapp after change in watched files", e);
		}
	}
}
// EOF